﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace MDCAdminTool.Commands
{
    public class OpenFileDialog : CommandBinding
    {
        public OpenFileDialog()
        {
            Command = Application.Current.Resources["OpenFileDialog"] as ICommand;
            CanExecute += OnCanExecute;
            Executed   += OnExecuted;
        }

        protected void OnExecuted( object sender , ExecutedRoutedEventArgs e )
        {
            var txb = e.Source as TextBox;
            var dlg = new Microsoft.Win32.OpenFileDialog
                          {
                              DefaultExt = ".config",
                              Filter     = "Config files (.config)|*.config"
                          };

            var result = dlg.ShowDialog();
            if (txb != null)
            {
                txb.Text = dlg.FileName;
                txb.Focus();
            }

            // OpenXmlTabItem(txb);
        }

        private void OpenXmlTabItem(TextBox txb)
        {
            var xml = new TabItem { Header = "ConfigCacheName File" };
            xml.ContentTemplate = Application.Current.FindResource( "XMLContentTemplate" ) as DataTemplate;
            var f = xml.FindName("frame") as Frame;
            if (f != null) f.Navigate(new Uri(txb.Text));
            var tabCon = Application.Current.Properties["TabControl"] as TabControl;
            if (tabCon != null) tabCon.Items.Add( xml );
        }

        protected void OnCanExecute( object sender , CanExecuteRoutedEventArgs e )
        {
            e.CanExecute = true;
        }
    }
}